﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
using WebAutomation.Browsers;

namespace WebAutomation
{
    public class TextBoxCommand : CommandBase
    {
        public TextBoxCommand()
        {
            
        }

        public TextBoxCommand(WebBrowserObject browserObject)
        {
            this.Initialize(browserObject);

        }

        public override bool ExecuteCommand(WebBrowserObject browserObject, string[] parameter, string url, string testRepo, string testResultLocation, string dbConnString, ref DataSet dataFromDB, ref TestLineResult testLineResult, ref bool stopTest, WebAutoUtils.ITestDataExceptionRules testDataExceptionRules)
        {
            WebBrowserObject.ElementProperties txtField = new WebBrowserObject.ElementProperties();
            string command = parameter[0];
            testLineResult.LineCommand = command;
            testLineResult.LineParameter = parameter[1];
            if(this.BrowserObject==null)
            {
                this.BrowserObject = browserObject;
            }
            try
            {
                
                switch(command.ToLower())
                {
                    case "keypressenter":
                        var id = parameter[1].Split(':')[0];
                        var keyName = "";
                        txtField = GetTextBox(id);
                        this.BrowserObject.KeyPressEnter(txtField.Element, keyName, this.BrowserObject);
                        testLineResult.LinePassed = true;
                        break;


                    case "type":
                        if(!parameter[1].Contains(":"))
                        {
                            testLineResult.IsFrameworkError = false;
                            testLineResult.LineMessage = "Error.The command doesnot contain a id or name for the textbox.The command format must contain eg. txtName:myusername";
                            testLineResult.LinePassed = false;
                            return false;
                        }
                        var idOrName = parameter[1].Split(':')[0];
                        var value = parameter[1].Split(':')[1];
                        string origValue = value;
                        if (value.Contains("Excel["))
                        {
                            int excelColumn = Convert.ToInt32(value.Replace("Excel[","").Replace("]",""));
                            value = TestFileReader.GetExcelColumnData(excelColumn);

                        }
                        else
                        {
                            if (value.ToLower().StartsWith("random("))
                            {

                                Random r = new Random();
                                value = r.Next(5000, 12345678).ToString();
                                if (value.Length > 7)
                                {
                                    value = value.Substring(0, 7);
                                }
                                string saveVarname = origValue.Replace("Random(", "").Replace(")", "");
                                bool saveToVariable = saveVarname.Length > 0;
                                if (saveToVariable)
                                {
                                    string value2 = value;
                                    if (saveVarname.Contains("+"))
                                    {
                                        string[] saveVarnameArray = saveVarname.Split('+');
                                        saveVarname = saveVarnameArray[1];

                                        value2 = saveVarnameArray[0] + value;
                                    }

                                    TestCommands.SetVariable(saveVarname, value2);
                                }
                            }
                            else
                            {
                                if (value.ToLower().Contains("random()"))
                                {
                                    Random r = new Random();
                                    value = "";
                                    value = r.Next(5).ToString();
                                    value += r.Next(5).ToString();
                                    value += r.Next(5).ToString();
                                    value += r.Next(5).ToString();
                                    value = origValue.Replace("Random()", value);
                                }
                            }
                        }

                        txtField = GetTextBox(idOrName);
                        if (!txtField.Exists)
                        {
                            Thread.Sleep(3000);
                            txtField = GetTextBox(idOrName);
                        }

                        if (txtField.Exists)
                        {
                            TypeText(value, txtField.Element);
                            testLineResult.LinePassed = true;
                        }else
                        {
                            testLineResult.LineMessage = "Could not find textbox with id or name " + idOrName;
                            testLineResult.LinePassed = false;
                        }
                        
                        
                        break;
                }

            }
            catch (Exception ex)
            {
                testLineResult.IsFrameworkError = true;
                testLineResult.LineMessage = "Error." + ex.Message + "." + ex.StackTrace;
                testLineResult.LinePassed = false;
            }
            return testLineResult.LinePassed;
        }

        public virtual void TypeText(string valueToType,object txtField)
        {
            BrowserObject.TypeText(txtField, valueToType,this.BrowserObject);
        }

        public WebBrowserObject.ElementProperties GetTextBox(string idOrName)
        {
            WebBrowserObject.ElementProperties txtField = new WebBrowserObject.ElementProperties();
            try
            {
                txtField = this.BrowserObject.TextField(Find.ByName(idOrName));
                if (!txtField.Exists)
                {
                    txtField = this.BrowserObject.TextField(Find.ById(idOrName));
                }
                if (!txtField.Exists)
                {
                    txtField = _getTextBoxFromIFrame(this.BrowserObject, idOrName);
                }
              
            }
            catch (UnauthorizedAccessException ex) { }
            if (!txtField.Exists)
            {
                txtField = _getTextBoxFromIFrame(this.BrowserObject, idOrName);
            }

            
            return txtField;
        }

        private WebBrowserObject.ElementProperties _getTextBoxFromIFrame(WebBrowserObject browserObject, string idOrName)
        {
            WebBrowserObject.ElementProperties txtField = new WebBrowserObject.ElementProperties();
            try
            {
                if (browserObject.Frames().Count > 0)
                {
                    for (int i = 0; i <= browserObject.Frames().Count - 1; i++)
                    {

                        browserObject.WaitForCompleteIFrame(i, 5000);
                        txtField = browserObject.TextFieldIFrame(i,Find.ByName(idOrName));
                        if (!txtField.Exists)
                        {
                            txtField = browserObject.TextFieldIFrame(i, Find.ById(idOrName));
                        }
                        if (!txtField.Exists)
                        {
                            txtField = browserObject.TextFieldIFrame(i, Find.ByClass(idOrName));
                        }
                        if (txtField.Exists)
                        {
                            break;
                        }
                    }

                }
               
            }catch(UnauthorizedAccessException ex)
            {
                
            }
            return txtField;
        }

    }
}
